package com.leaf.u.basehttp.http.request;

import com.leaf.u.basehttp.http.HttpEngine;
import com.leaf.u.basehttp.http.inter.RequestInterceptor;
import com.leaf.u.basehttp.http.okimpl.LeafRequest;
import com.leaf.u.basehttp.http.response.LeafResponse;

import java.io.IOException;
import java.util.List;

/**
 * Created by bz on 2017/6/7.
 */

public class RequestInterceptorChain implements RequestInterceptor.Chain {
    private final LeafRequest request;
    private final HttpEngine engine;
    private final List<RequestInterceptor> interceptors;
    private LeafResponse response;
    private int index = 0;
    private int looper = 0;
    private boolean isTermination = false;

    public RequestInterceptorChain(List<RequestInterceptor> interceptors, LeafRequest request, HttpEngine engine) {
        this.request = request;
        this.engine = engine;
        this.interceptors = interceptors;
    }

    @Override
    public LeafRequest request() {
        return this.request;
    }

    @Override
    public int getLooper() {
        return looper;
    }


    @Override
    public HttpEngine engine() {
        return this.engine;
    }
    /**
     *
     * @return
     */
    protected boolean isFinish() {
        RequestInterceptor requestInterceptor = interceptors.get(index - 1);
        if (requestInterceptor instanceof ServerInterceptor) {
            // 如果是服务拦截器则完成本次请求
            return true;
        } else {
            if (isTermination) {
                return true;
            }
            // 如果是其他分支返回则移除该拦截器并返回false重新再遍历一遍拦截器
            interceptors.remove(requestInterceptor);
            index = 0;
            looper++;
            return false;
        }
//        return interceptors.size() <= index || interceptors.get(index).endding();
    }


    @Override
    public LeafResponse proceed(LeafRequest request) throws IOException {
        if (index >= interceptors.size()) {
            return response;
        }
        RequestInterceptor interceptor = interceptors.get(index);
        index++;
        response = interceptor.interceptor(this);
        return response;
    }

    @Override
    public void termination() {
        isTermination = true;
    }
}
